<template>
    <div class="course">
       
        <!-- 课程模块 -->
        <div class="mcourse" v-loading="loading">
            <div 
                v-for="(course, index) in paginatedCourseList" 
                :key="index" 
                class="card-link"
            >
                <div class="card">
                    <div class="touxiang">
                        <el-upload
                            class="avatar-uploader"
                            action="#"
                            :auto-upload="false"
                            :show-file-list="false"
                            :on-change="(file) => handleAvatarChange(file, course)"
                            :before-upload="beforeAvatarUpload"
                        >
                            <img 
                                v-if="course.avatar" 
                                :src="course.avatar" 
                                class="avatar"
                                @error="handleImageError"
                            >
                            <i v-else class="iconfont icon-touxiang"></i>
                            <div class="upload-hover-text">点击上传</div>
                        </el-upload>
                        <h2>{{ course.courseclassT || '未知课程' }}</h2>
                    </div>
                    <div class="info">
                        <span><i class="iconfont icon-yonghutubiao"> {{ course.studentCount || 0 }}</i></span>
                        <span><i class="iconfont icon-wenjian-wendangtubiao"> {{ course.homeworkCount || 0 }}</i></span>
                    </div>
                    <!-- 添加进入班级按钮 -->
                    <div class="enter-class-button">
                        <router-link 
                            :to="{
                                path: '/layout/homework',
                                query: { courseclassS: course.courseclassT }
                            }"
                        >
                            进入班级
                        </router-link>
                    </div>
                </div>
            </div>
            
            <!-- 分页组件移到这里 -->
            <div class="pagination-wrapper">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[8, 12, 16, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
        </div>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            courses: [],
            loading: false,
            currentPage: 1,
            pageSize: 8,
            total: 0,
            userInfo: null,
            uploadData: {
                type: 'avatar'
            }
        }
    },
    computed: {
        paginatedCourseList() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.courses.slice(start, end);
        }
    },
    methods: { 
        // 获取教师相关的课程
        async getTeacherCourses() {
            try {
                this.loading = true;
                this.userInfo = JSON.parse(localStorage.getItem('users'));
                if (!this.userInfo || !this.userInfo.userId) {
                    this.$message.error('未找到用户信息，请重新登录');
                    return;
                }

                const response = await axios.post('http://localhost:9999/teach/getTeach', 
                    this.userInfo,
                    {
                        headers: {
                            'Content-Type': 'application/json;charset=UTF-8'
                        }
                    }
                );

                if (!response.data) {
                    this.$message.info('未获取到课程数据');
                    return;
                }

                this.courses = Array.isArray(response.data) ? response.data : [];
                this.total = this.courses.length;
                
                // 为每个课程获取作业数和学生数
                await this.updateAllCoursesInfo();
            } catch (error) {
                console.error('获取教师课程失败:', error.response || error);
                this.$message.error(`获取课程列表失败: ${error.response?.data?.message || error.message}`);
            } finally {
                this.loading = false;
            }
        },

        // 新增：更新所有课程的信息
        async updateAllCoursesInfo() {
            try {
                const updatePromises = this.courses.map(async (course) => {
                    if (course.courseclassT) {
                        const [homeworkCount, studentCount] = await Promise.all([
                            this.getHomeworkTotal(course.courseclassT),
                            this.getClassStudentNum(course.courseclassT)
                        ]);
                        
                        // 直接更新课程对象
                        course.homeworkCount = homeworkCount;
                        course.studentCount = studentCount;
                    }
                });

                await Promise.all(updatePromises);
            } catch (error) {
                console.error('更新课程信息失败:', error);
            }
        },

        // 修改获取作业总数的方法
        async getHomeworkTotal(courseclassT) {
            try {
                if (!courseclassT) {
                    console.warn('课程名称为空');
                    return 0;
                }
                const formattedCourseName = courseclassT.trim();
                const response = await axios.post('http://localhost:9999/homework/getTotal', 
                    { courseclass: formattedCourseName }
                );
                return response.data || 0;
            } catch (error) {
                console.error('获取班级作业总数失败:', error);
                return 0;
            }
        },

        // 修改获取学生人数的方法
        async getClassStudentNum(courseclassT) {
            try {
                if (!courseclassT) {
                    console.warn('课程名称为空');
                    return 0;
                }
                const formattedCourseName = courseclassT.trim();
                const response = await axios.post('http://localhost:9999/selectcourse/getClassStudentNum', 
                    { courseclassS: formattedCourseName }
                );
                return response.data || 0;
            } catch (error) {
                console.error('获取班级学生人数失败:', error);
                return 0;
            }
        },

        handleCurrentChange(newPage) {
            this.currentPage = newPage;
        },

        handleSizeChange(newSize) {
            this.pageSize = newSize;
            this.currentPage = 1;
        },

        async fetchCourseList() {
            try {
                const res = await axios.get('http://localhost:9999/teach/getAll');
                this.courseList = res.data;
                this.total = this.courseList.length;
            } catch (error) {
                console.error('获取课程列表失败:', error);
                this.$message.error('获取课程列表失败');
            }
        },

        handleAvatarChange(file, course) {
            // 文件类型检查
            const isJPG = file.raw.type === 'image/jpeg';
            const isPNG = file.raw.type === 'image/png';
            const isLt2M = file.raw.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
                return;
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
                return;
            }

            // 使用 FileReader 预览图片
            const reader = new FileReader();
            reader.onload = (e) => {
                // 确保在 Vue 的响应式系统中更新数据
                this.$set(course, 'avatar', e.target.result);
                console.log('Avatar updated:', course.avatar); // 调试日志
                this.$message.success('头像上传成功！');
            };
            reader.onerror = (e) => {
                this.$message.error('头像上传失败，请重试！');
                console.error('FileReader error:', e); // 调试日志
            };
            reader.readAsDataURL(file.raw);
        },

        beforeAvatarUpload(file) {
            return false; // 阻止自动上传
        },

        handleImageError() {
            console.error('Image failed to load'); // 调试日志
            this.$message.error('头像加载失败');
        }
    },
    mounted() {
        this.getTeacherCourses();
    }
}

</script>

<style lang="less" scoped>
.course {
    position: relative;
    padding: 20px;
    background-color: #f5f5f5;  // 背景颜色
}

.search {
    margin-bottom: 20px;
}

.mcourse {
    background: white;
    width: 1300px;
    min-height: 800px;
    margin: 90px auto;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 30px;
    padding: 20px;
    border-radius: 8px;  // 圆角
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);  // 阴影
}

/* 添加一个新的类来包裹 card，以确保样式不被 RouterLink 影响 */
.card-link {
    width: 100%;
    text-decoration: none;
    color: inherit;

    &:hover {
        text-decoration: none;
    }

    .card {
        width: 100%;
        height: 300px;
        background-color: white;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        text-align: center;
        position: relative;
        transition: transform 0.3s;  // 动画效果

        &:hover {
            transform: translateY(-10px);  // 悬停效果
        }
    }

    .card .touxiang {
        margin-top: 40px;
    }

    .card h2 {
        font-size: 18px;
        margin: 10px 0;
        color: #333;
    }

    .card .info {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: rgba(255, 255, 255, 0.9);
        padding: 15px;
        box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
    }

    .card .info span {
        display: inline-block;
        margin-right: 20px;
        font-size: 14px;
        color: #666;
    }

    .card .info i {
        margin-right: 5px;
        font-size: 18px;
        color: #409EFF;
    }
}

/* 新增分页包装器样式 */
.pagination-wrapper {
    position: sticky;
    bottom: 0;
    left: 0;
    right: 0;
    grid-column: 1 / -1;
    display: flex;
    justify-content: center;
    background-color: white;
    padding: 10px 0;
    margin-top: 20px;
    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}

/* 添加媒体查询以确保响应式布局 */
@media screen and (max-width: 1400px) {
    .mcourse {
        width: 95%;
        grid-template-columns: repeat(3, 1fr);
    }
}

@media screen and (max-width: 1024px) {
    .mcourse {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media screen and (max-width: 768px) {
    .mcourse {
        grid-template-columns: repeat(1, 1fr);
    }
}

.avatar-uploader {
    position: relative;
    display: inline-block;
    cursor: pointer;
    
    .avatar {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        object-fit: cover;
        display: block;
        margin: 25px auto;
        border: 2px solid #409EFF; // 添加边框使头像更明显
    }

    .iconfont {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        font-size: 100px;
        display: inline-block;
        line-height: 100px;
        color: #409EFF;
        margin: 25px auto;
    }

    .upload-hover-text {
        display: none;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #fff;
        background: rgba(0, 0, 0, 0.6);
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        z-index: 1;
    }

    &:hover {
        .upload-hover-text {
            display: block;
        }

        .avatar, .iconfont {
            opacity: 0.8;
        }
    }
}

.touxiang {
    text-align: center;
    margin-top: 40px;
}

.enter-class-button {
    margin-top: 10px;
    text-align: center;

    a {
        display: inline-block;
        padding: 5px 15px;
        background-color: #409EFF;
        color: white;
        border-radius: 4px;
        text-decoration: none;
        transition: background-color 0.3s;

        &:hover {
            background-color: #66b1ff;
        }
    }
}
</style>